package com.atguigu.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * 测试事务
 * @author: malichun
 * @date 2022/5/17 0017 21:29
 */
public class CustomProducerTransactions {

    public static void main(String[] args) {
        // 1. 创建kafka生产者配置对象
        Properties properties = new Properties();
        // 2. 给kafka配置对象添加信息： bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.12:9092");
        // key, value序列化（必须）： key.serializer, value.serializer
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // 设置事务 id（必须），事务 id 任意起名
        properties.setProperty(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transaction_id_01");
  // 3. 创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        kafkaProducer.initTransactions();

        kafkaProducer.beginTransaction();
        try {
            // 4.调用send方法，发送消息
            for (int i = 0; i < 5; i++) {
                kafkaProducer.send(new ProducerRecord<>("first", "atguigu " + i));
            }
             int i = 1 /0;
            kafkaProducer.commitTransaction(); // 提交事务
        }catch (Exception e){
            kafkaProducer.abortTransaction(); // 终止事务
        }finally {
            // 5.关闭资源
            kafkaProducer.close();
        }
    }

}
